package com.yazi.mxz.admin.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.yazi.mxz.common.controller.BaseController;
import com.yazi.mxz.common.entity.beans.Article;
import com.yazi.mxz.common.entity.beans.Category;
import com.yazi.mxz.common.service.ArticleService;
import com.yazi.mxz.common.service.CategoryService;
import com.yazi.mxz.admin.common.MyConfig;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.tool.PageLink;
import com.myframework.smhj.hibernate.Paging;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.Page;
import com.myframework.smhj.jackson.result.ObjectResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("articleController")
@RequestMapping("/article")
public class ArticleController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(ArticleController.class);

	@Resource
	ArticleService articleService;
	@Resource
	CategoryService categoryService;

	@RequestMapping("/list")
	public String list(Article article, Searching si, Model model) {
		log.debug("管理->进入文章列表页面");
		Page<Article> page = articleService.list(article, si);
		PageLink pageLink = new MyPageLink(page.getPaging());
		model.addAttribute("articleList", page.getList());
		model.addAttribute("pageLink", pageLink);
		model.addAttribute("article", article);
		model.addAttribute("searchWord", si.getSearchWord());
		return "article_list";
	}

	@RequestMapping("/addOrEdit")
	public String addOrEdit(Article article, Model model) {
		Long articleId = article.getArticleId();
		if (null != articleId) {
			log.debug("管理->进入文章编辑页面：articleId={}", articleId);
			article = articleService.one(articleId);
		} else {
			log.debug("管理->进入文章添加页面");
		}
		model.addAttribute("article", article);
		return "article_addOrEdit";
	}

	@RequestMapping("/addOrEditDo")
	public String addOrEditDo(Article article) {
		log.debug("管理->保存（添加/更新）文章");
		try {
			articleService.addOrEdit(article);
		} catch (MyException e) {
			log.error("添加/更新文章信息异常:", e);
		}
		return "redirect:/article/list";
	}

	@RequestMapping("/generate")
	public String generate() {
		log.debug("管理->进入静态生成页面");
		return "article_generate";
	}

	@RequestMapping("/generateHelpDo/json")
	@ResponseBody
	public ObjectResult<?> generateHelpDo(GenerateSetting setting, Model model) {
		log.debug("管理->生成'帮助中心'静态页面:catId={},pageSize={},nowPage={}",
				new Object[] { setting.getCatId(), setting.getPi().getPageSize(),
						setting.getPi().getNowPage() });
		ObjectResult<Paging> jsonResult = new ObjectResult<Paging>();
		String encoding = MyConfig.getInstance().getEncoding();
		Long catId = setting.getCatId();
		Searching paging = setting.getPi();
		// eg: /opt/app/hcd/template/article/help.ftl
		String templateFile = MyConfig.getInstance().getHome() + "/template" + setting.getTemplate();
		// eg: /opt/app/hcd/template/article
		String templatePath = templateFile.substring(0, templateFile.lastIndexOf("/"));
		// eg: help.ftl
		String templateFileName = templateFile.substring(templateFile.lastIndexOf("/") + 1);;
		// eg /opt/app/hcd/static/article.war
		String savePath = MyConfig.getInstance().getHome() + "/static" + setting.getGeneratePath();
		try {
			File saveDir = new File(savePath);
			if (!saveDir.exists())
				saveDir.mkdirs();
			Configuration cfg = new Configuration();
			//cfg.setDefaultEncoding(MyConfig.getInstance().getEncoding());
			cfg.setDirectoryForTemplateLoading(new File(templatePath));
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			cfg.setDefaultEncoding(encoding);
			Template template = cfg.getTemplate(templateFileName);
			template.setEncoding(encoding);
			Category rootCat = categoryService.one(catId);
			Page<Article> page = articleService.listByRootCatId(catId, paging);
			List<Article> list = page.getList();
			for (Article article : list) {
				FileOutputStream outStream = new FileOutputStream(new File(saveDir,
						article.getArticleId() + ".html"));
				OutputStreamWriter writer = new OutputStreamWriter(outStream, encoding);
				BufferedWriter sw = new BufferedWriter(writer);
				Map<String, Object> rootMap = new HashMap<String, Object>();
				rootMap.put("article", article);
				rootMap.put("rootCat", rootCat);
				rootMap.put("st", MyConfig.getInstance());
				// 模板引擎解释模板
				template.process(rootMap, sw);
				sw.flush();
				sw.close();
				outStream.close();
			}
			jsonResult.setResult(page.getPaging());
			jsonResult.setOkMessage("生成成功");
		} catch (Exception e) {
			log.error("'帮助中心'静态页生成异常:", e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		return jsonResult;
	}

	public static class GenerateSetting {
		/**
		 * 目标内容类
		 */
		Long catId;
		/**
		 * 模板目录
		 */
		String templatePath;
		/**
		 * 模板文件名
		 */
		String template;
		/**
		 * html存放目录
		 */
		String generatePath;
		/**
		 * 分页信息
		 */
		Searching si = new Searching();

		public Long getCatId() {
			return catId;
		}

		public void setCatId(Long catId) {
			this.catId = catId;
		}

		public String getTemplatePath() {
			return templatePath;
		}

		public void setTemplatePath(String templatePath) {
			this.templatePath = templatePath;
		}

		public String getTemplate() {
			return template;
		}

		public void setTemplate(String template) {
			this.template = template;
		}

		public String getGeneratePath() {
			return generatePath;
		}

		public void setGeneratePath(String generatePath) {
			this.generatePath = generatePath;
		}

		public Searching getPi() {
			return si;
		}

		public void setPi(Searching si) {
			this.si = si;
		}

	}

}
